package com.szx.kaihei.handler;

import cn.hutool.core.map.MapUtil;
import com.szx.kaihei.exceptions.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Object> handleCustomException(CustomException e) {
        log.error("异常信息: {}", e.getMessage());
        return ResponseEntity.status(500).body(MapUtil.<String, Object>builder()
                .put("code", e.getCode())
                .put("message", e.getMessage())
                .build()
        );
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception e) {
        log.error("异常信息: {}", e.getMessage());
        return ResponseEntity.status(500).body(MapUtil.<String, Object>builder()
                .put("code", 500)
                .put("message", e.getMessage())
                .build()
        );
    }

    //处理参数效验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数效验异常信息: {}", e.getBindingResult().getFieldError().getDefaultMessage());
        return ResponseEntity.status(400).body(MapUtil.<String, Object>builder()
                .put("code", 400)
                .put("message", e.getBindingResult().getFieldError().getDefaultMessage())
                .build()
        );
    }
}
